<?php
/**
 * 景点
 */
namespace App\Http\Controllers\Admin\Finance;


use App\Http\Controllers\Admin\Business\Service\Combo;
use App\Http\Controllers\Admin\Business\Service\ComboActivities;
use App\Http\Controllers\Admin\Business\Repository\ComboOrder as ComboOrderRepository;
use App\Http\Controllers\Admin\Finance\Service\Account;
use App\PayOrder;
use App\Setting;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
use Maatwebsite\Excel\Facades\Excel;

class AccountController extends Controller
{
    private $manager;
    private $repository;
    private $request;
    private $viewPrefix = 'admin.finance.account.';
    private $routePrefix = 'admin.finance.account';
    public function __construct (Request $request)
    {
        $this->manager = new Account();
        $this->repository = new ComboOrderRepository();
        $this->request = $request;
    }

    /**
     * 文章列表
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(){
        if(isset($this->request->act)){
            $act = $this->request->act;
            return $this->{$act}();
        }else{

            return view($this->viewPrefix.'index',[
                'manager'   =>  $this->manager,
                'routePrefix'   =>  $this->routePrefix,
                'types' =>  $this->manager->getTypeList()
            ]);
        }

    }

    /**
     * ajax列表
     * @return array
     */
    public function indexAjax(){

        return $this->page_json_render($this->manager->getPageList($this->request));
    }

    public function read($id){
        $model  = $this->manager->getComboOrder($id);
        $sysRate = [
            'rate'  =>  Setting::getConfig('rate','分销设置'),
            'top_rate'  =>  Setting::getConfig('topRate','分销设置')
        ];
        $reduce_type = ComboActivities::REDUCE;
        return view($this->viewPrefix.'read',[
            'manager'   =>  $this->manager,
            'routePrefix'   =>  $this->routePrefix,
            'model' =>  $model,
            'rate_type_user' =>  Combo::RATE_TYPE_USER,
            'sysRate'   =>  $sysRate,
            'reduce_type'   =>  $reduce_type
        ]);
    }
    /**
     * @return array
     */
    private function hide(){
        $this->manager->hide($this->request->id);
        return  ['info'  =>  'success'];
    }
    private function show(){
        $this->manager->show($this->request->id);
        return  ['info'  =>  'success'];
    }
    public function order(Request $request){//订单统计
        //查询

       $commbo= \App\Http\Controllers\Admin\Business\Repository\Combo::select('id','title')->get()->toArray();
      $total=    \Cache::remember('total',1,function(){
          return  \DB::table('pay_orders')
              ->join('combo_orders','combo_orders.outTradeNo','=','pay_orders.out_trade_no')
              ->select('combo_orders.combo_id',\DB::raw('sum(combo_orders.total_num) as total'))
              ->groupBy('combo_orders.combo_id')
              ->where('pay_orders.is_pay','=',1)
              ->where('pay_orders.created_at','>',Carbon::today())
              ->where('pay_orders.created_at','<',Carbon::now())
              ->pluck('total','combo_orders.combo_id')->toArray();
      });
        $totalTiket=   \Cache::remember('totalTiket',1,function(){
            return  \DB::table('pay_orders')
                ->join('combo_orders','combo_orders.outTradeNo','=','pay_orders.out_trade_no')
                ->select('combo_orders.combo_id',\DB::raw('sum(combo_orders.total_num) as total'))
                ->groupBy('combo_orders.combo_id')
                ->where('pay_orders.is_pay','=',1)
                ->where('combo_orders.is_send','=',1)
                ->where('pay_orders.created_at','>',Carbon::today())
                ->where('pay_orders.created_at','<',Carbon::now())
                ->pluck('total','combo_orders.combo_id')->toArray();
        });
        $todayTotal=  \Cache::remember('todatTotal',1,function(){
            return  \DB::table('pay_orders')
                ->join('combo_orders','combo_orders.outTradeNo','=','pay_orders.out_trade_no')
                ->select('combo_orders.combo_id',\DB::raw('count(combo_orders.total_num) as total'))
                ->groupBy('combo_orders.combo_id')
                ->where('pay_orders.is_pay','=',1)
                ->where('pay_orders.created_at','>',Carbon::yesterday())
                ->where('pay_orders.created_at','<',Carbon::today())
                ->pluck('total','combo_orders.combo_id')->toArray();
        });

        $todayTotalTicket=  \Cache::remember('todatTotalTicket',1,function(){
            return  \DB::table('pay_orders')
                ->join('combo_orders','combo_orders.outTradeNo','=','pay_orders.out_trade_no')
                ->select('combo_orders.combo_id',\DB::raw('sum(combo_orders.total_num) as total'))
                ->groupBy('combo_orders.combo_id')
                ->where('pay_orders.is_pay','=',1)
                ->where('pay_orders.created_at','>',Carbon::yesterday())
                ->where('pay_orders.created_at','<',Carbon::today())
                ->where('combo_orders.is_send','=',1)
                ->pluck('total','combo_orders.combo_id')->toArray();
        });

        $mounthTotal=  \Cache::remember('mounthTotal',1,function(){
            return \DB::table('pay_orders')
                ->join('combo_orders','combo_orders.outTradeNo','=','pay_orders.out_trade_no')
                ->select('combo_orders.combo_id',\DB::raw('sum(combo_orders.total_num) as total'))
                ->groupBy('combo_orders.combo_id')
                ->where('pay_orders.is_pay','=',1)
                ->where('pay_orders.created_at','>',$this->GetTheMonth()[0])
                ->where('pay_orders.created_at','<',$this->getTheMonth()[1])
                ->pluck('total','combo_orders.combo_id')->toArray();
        });

        $mounthTotalTicket=  \Cache::remember('mounthTotalTicket',1,function(){
            return \DB::table('pay_orders')
                ->join('combo_orders','combo_orders.outTradeNo','=','pay_orders.out_trade_no')
                ->select('combo_orders.combo_id',\DB::raw('sum(combo_orders.total_num) as total'))
                ->groupBy('combo_orders.combo_id')
                ->where('pay_orders.is_pay','=',1)
                ->where('pay_orders.created_at','>',$this->GetTheMonth()[0])
                ->where('pay_orders.created_at','<',$this->getTheMonth()[1])
                ->where('combo_orders.is_send','=',1)
                ->pluck('total','combo_orders.combo_id')->toArray();
        });

        $totalPrice=  \Cache::remember('totalPrice',1,function(){
            return \DB::table('pay_orders')
                ->join('combo_orders','combo_orders.outTradeNo','=','pay_orders.out_trade_no')
                ->select('pay_orders.price')
                ->where('pay_orders.is_pay','=',1)
                ->where('pay_orders.created_at','>',Carbon::today())
                ->where('pay_orders.created_at','<',Carbon::now())
                ->sum('pay_orders.total_fee');
        });

        $todayPrice=  \Cache::remember('todatPrice',1,function(){
            return \DB::table('pay_orders')
                ->join('combo_orders','combo_orders.outTradeNo','=','pay_orders.out_trade_no')
                ->select('pay_orders.price')
                ->where('pay_orders.is_pay','=',1)
                ->where('pay_orders.created_at','>',Carbon::yesterday())
                ->where('pay_orders.created_at','<',Carbon::today())
                ->sum('pay_orders.total_fee');
        });

        $mounthPrice=  \Cache::remember('mounthPrice',1,function(){
            return \DB::table('pay_orders')
                ->join('combo_orders','combo_orders.outTradeNo','=','pay_orders.out_trade_no')
                ->select('pay_orders.price')
                ->where('pay_orders.is_pay','=',1)
                ->where('pay_orders.created_at','>',$this->GetTheMonth()[0])
                ->where('pay_orders.created_at','<',$this->getTheMonth()[1])
                ->sum('pay_orders.total_fee');
        });

        foreach ($commbo as &$v){
            $v['total']=$total[$v['id']] ?? 0;
            $v['totalTicket']=$totalTiket[$v['id']] ?? 0;
            $v['todayTotal']=$todayTotal[$v['id']] ?? 0;
            $v['todayTotalTicket']=$todayTotalTicket[$v['id']] ?? 0;
            $v['mounthTotal']=$mounthTotal[$v['id']] ?? 0;
            $v['mounthTotalTicket']=$mounthTotalTicket[$v['id']] ?? 0;
        }
       // dd($mounthTotal);
        if($request->exprot){
            $this->exportReport($commbo,$totalPrice,$todayPrice,$mounthPrice);
        }else{
            return view($this->viewPrefix.'order',compact('commbo','totalPrice','todayPrice','mounthPrice'));
        }
    }
    public function GetTheMonth(){//获取指定日期所在月的第一天和最后一天
        $firstday = date("Y-m-01 00:00:00",time());
        $lastday = date("Y-m-d H:i:s",strtotime("$firstday +1 month"));
        return array($firstday,$lastday);
    }
    public function exportReport($commbo,$totalPrice,$todayPrice,$mounthPrice){
        $cellData=[];
        foreach ($commbo as $v){
            $temp=[
                $v['title'],
                $v['total'],
                $v['totalTicket'],
                $v['todayTotal'],
                $v['todayTotalTicket'],
                $v['mounthTotal'],
                $v['mounthTotalTicket']
            ];
            $cellData[]=$temp;
        }

        Excel::create('支付订单',function($excel) use ($cellData,$totalPrice,$todayPrice,$mounthPrice){


            $excel->sheet('orders', function($sheet) use ($cellData,$todayPrice,$totalPrice,$mounthPrice){
                $sheet->mergeCells('B1:C1');
                $sheet->mergeCells('D1:E1');
                $sheet->mergeCells('F1:G1');

                $sheet->mergeCells('B2:C2');
                $sheet->mergeCells('D2:E2');
                $sheet->mergeCells('F2:G2');

                $sheet->row(1, array(
                    '', '当前汇总','','前一日订单合计(00:00-24:00)','','本月订合计（1-30/31号)'
                ));
                 $sheet->row(2, array(
                    '营业收入','合计营业额:'.$totalPrice/100,'','合计营业额:'.$todayPrice/100,'','合计营业额:'.$mounthPrice/100
                ));
                $sheet->row(3, array(
                    '','订单数量汇总','门票发放汇总','订单数量汇总','门票发放汇总','订单数量汇总','门票发放汇总'
                ));
                $sheet->rows($cellData);


            });
        })->export('xls');
    }
}
